import pygame
import random


SCREEN = pygame.Rect(0, 0, 480, 710)

CREATE_EVENT = pygame.USEREVENT

BULLET_EVENT = pygame.USEREVENT+1


class GameSprites(pygame.sprite.Sprite):
    def __init__(self, image, speed=1):
        super().__init__()
        self.image = pygame.image.load(image)
        self.speed = speed
        self.rect = self.image.get_rect()
        self.speed = speed



    def update(self):
        self.rect.y += self.speed
        # self.rect.x += 1


class BackGround(GameSprites):
    def __init__(self, is_flag=False):
        # is_flag判断是否为另一张图像
        # False表示第一张图像
        # Ture表示另外一张图像
        # 两张图像交替循环
        # 传图片
        super().__init__("./图片/background2.png")
        if is_flag:
            # 如果是第二张图片 初始位置为-self.rect.height
            self.rect.y = -self.rect.height

    # def __init__(self,new_image):
    #   super().init__(new_image)
    def update(self):

        super().update()
        if self.rect.y >= SCREEN.height:
            self.rect.y = -self.rect.height

# 创建战机类
class Hero(GameSprites):
    def __init__(self):
        super().__init__("./图片/hero.png", speed=0)
        self.rect.center = SCREEN.center
        self.rect.bottom = SCREEN.bottom+10
        self.bullet = pygame.sprite.Group()

    def update(self):
        self.rect.x += self.speed
        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.right > SCREEN.right:
            self.rect.right = SCREEN.right

    def fire(self):
        # print("发射子弹")
        for i in (0, 1):
            bullet = Bullet()
            bullet.rect.bottom = self.rect.y-i*20
            bullet.rect.center = self.rect.center
            self.bullet.add(bullet)

# 创建敌机类
class Enemy(GameSprites):
    def __init__(self):
        super().__init__("./图片/enemy.png")
        self.speed = 1  # 设置敌机飞行速度
        self.rect.y = -self.rect.height
        self.rect.x = random.randint(0, SCREEN.width-self.rect.width)

    def update(self):
        super().update()

        if self.rect.y >= SCREEN.height:
            self.kill()

    def __del__(self):
        print("敌机消失")

# 创建子弹类
class Bullet(GameSprites):
    def __init__(self):
        super().__init__("./图片/bullet.png", speed=-2)

    def update(self):
        super().update()
        if self.rect.y < SCREEN.y:
            self.kill()

    def __del__(self):
        print("子弹消失")